<template>
  <!-- 模板内容保持不变 -->
  <div class="home" style="width: 100%; padding: 8px;">
    <!-- 顶部 -->
    <div
      style="background: white; border-radius: 8px; box-shadow: 0 0px 0px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 16px;">
      <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
        <span>清场智能指引：被查询人（{{ search.name }}）</span>
        <!-- 按钮区域 -->
        <div style="display: flex; gap: 8px;">
          <el-button type="primary" @click="$router.back()" size="big">返回</el-button>
          <el-button type="info" @click="goToPage('manage2')" size="big">送达与拘传指引</el-button>
          <el-button type="warning" @click="goToPage('manage3')" size="big">关联人财产查询</el-button>
          <el-button type="danger" @click="goToPage('manage4')" size="big">清场辅助与评估</el-button>
        </div>
      </div>
    </div>

    <!-- 原有布局：左侧和右侧内容 -->
    <div style="display: flex; gap: 16px; padding: 10px;">
      <!-- 左侧：搜索 + AI分析 + 基本信息 -->
      <div style="flex: 2; display: flex; flex-direction: column; gap: 16px;">
        <!-- 搜索栏 -->
        <div style="margin: 10px 0; display: flex; gap: 10px; flex-wrap: wrap;">
          <el-input clearable v-model="search.name" placeholder="请输入姓名" style="flex: 1; min-width: 200px;"
            @keyup.enter="load" />
          <el-input clearable v-model="search.phone" placeholder="请输入手机号" style="flex: 1; min-width: 200px;"
            @keyup.enter="load" />
          <el-input clearable v-model="search.idNumber" placeholder="请输入身份证号" style="flex: 1; min-width: 200px;"
            @keyup.enter="load" />
          <el-button type="primary" @click="load">查询</el-button>
        </div>

        <!-- 其余模板内容保持不变 -->
        <!-- AI智能分析结果展现（逐字打字效果） -->
        <div style="display: flex; align-items: center; margin: 16px 0; gap: 16px;">
          <img src="../../public/ai.png" alt="AI 图标"
            style="width: 64px; height: 64px; opacity: 1; transition: opacity 0.5s ease-in-out;" />
          <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8 }" clearable v-model="typedText"
            placeholder="AI 智能行动指引"
            style="flex: 1; font-size: 14px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 12px;" />
        </div>

        <!-- 展示名下不动产数据 -->
        <div
          style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px; overflow: hidden;">
          <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">名下不动产信息</h3>
          <!-- 修复：添加加载状态指示器 -->
          <div v-if="isLoadingRealEstate" style="text-align: center; padding: 20px;">
            <el-loading-spinner></el-loading-spinner>
            <p>加载中...</p>
          </div>
          <div v-else-if="hasData && realEstateInfo.length > 0"
            style="max-height: 400px; overflow-y: auto; overflow-x: auto;">
            <el-table :data="realEstateInfo" border stripe style="width: 100%;"
              :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold' }">
              <el-table-column prop="address" label="房产地址" min-width="200" />
              <el-table-column prop="ownerName" label="所有权人" width="120" />
              <el-table-column prop="buildingArea" label="建筑面积(㎡)" width="120" :formatter="formatNumber" />
              <el-table-column prop="landArea" label="土地面积(㎡)" width="120" :formatter="formatNumber" />
              <el-table-column prop="mortgageAmount" label="查控金额(万元)" width="130" :formatter="formatNumber" />
              <el-table-column prop="isSeized" label="是否查封" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.isSeized === '是' ? 'danger' : 'success'">
                    {{ row.isSeized === '是' ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="coOwnershipStatus" label="共有情况" width="120" />
              <el-table-column prop="landPurpose" label="土地用途" width="120" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="selectProperty(row)"
                    :disabled="selectedPropertyId === row.id">
                    {{ selectedPropertyId === row.id ? '已选择' : '选择' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else-if="hasData && realEstateInfo.length === 0" style="text-align: center; padding: 20px;">
            <p>暂无不动产信息</p>
          </div>
          <div v-else style="text-align: center; padding: 20px;">
            <p>请点击查询获取数据</p>
          </div>
        </div>



        <!-- 房产信息区域 -->
        <div
          style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 16px;">
          <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">房产信息分析</h3>
          <div style="display: flex; flex-direction: column; gap: 15px;">
            <!-- 房产价值评估 -->
            <div style="padding: 10px; border-bottom: 1px solid #eee;">
              <!-- 新增单价输入框和修改按钮 -->
              <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                <span>每平方米单价：</span>
                <el-input v-model.number="pricePerSquare" placeholder="请输入每平方米价格（万）" style="width: 200px;" type="number"
                  step="0.01" min="0" />
                <el-button type="primary" @click="updatePropertyValue" :disabled="!selectedPropertyId">
                  修改
                </el-button>
                <span v-if="!selectedPropertyId" style="color: #f56c6c; font-size: 12px;">
                  请先从房产列表中选择一个房产
                </span>
              </div>

              <span>房产价值趋势：</span>



              <div v-if="hasData && realEstateInfo.length > 0 && selectedProperty">
                <p style="margin: 5px 0;">
                  当前估值：¥{{ propertyValue }} 万
                  <span v-if="selectedProperty" style="font-size: 12px; color: #666; margin-left: 10px;">
                    ({{ selectedProperty.buildingArea }}㎡ × {{ pricePerSquare }}万/㎡)
                  </span>
                </p>
                <!-- 房产价值月度趋势图 -->
                <div ref="chartRefProperty" style="width: 100%; height: 80px; margin-top: 5px;"></div>
                <div style="margin-top: 10px;">
                  <el-progress :percentage="valueTrend === '上升' ? 70 : 30"
                    :status="valueTrend === '上升' ? 'success' : 'exception'" :show-text="false" :stroke-width="6" />
                  <p style="margin: 5px 0 0; font-size: 12px;">
                    近6个月趋势：<span :style="{ color: valueTrend === '上升' ? '#67c23a' : '#f56c6c' }">
                      {{ valueTrend }}
                    </span>
                  </p>
                </div>
              </div>
              <div v-else-if="hasData && realEstateInfo.length === 0">
                <p>无房产</p>
              </div>
              <div v-else>
                <p>暂无数据</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 关联人信息和订单使用频次并排 -->
        <div style="display: flex; gap: 16px; margin-bottom: 16px;">
          <!-- 关联人信息表格（添加分页功能） -->
          <div
            style="flex: 1; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
            <el-tabs>
              <el-tab-pane label="关联人信息">
                <span v-if="total > 0" style="color: #409EFF; margin-left: 10px;">共 {{ total }} 人</span>
                <el-table :data="currentPageData" border stripe style="width: 100%;">
                  <el-table-column prop="recName" label="关联人姓名" />
                  <el-table-column prop="recPhone" label="关联人电话" />
                  <el-table-column label="亲属关系" width="120">
                    <template #default="{ row }">
                      <el-tag type="info">{{ getRelation(row.recName) }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页控件 -->
                <div v-if="relatedPeople.length > 0 && hasData" style="margin-top: 15px; text-align: right;">
                  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5]"
                    :total="relatedPeople.length" layout="prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
                </div>

                <div v-else-if="relatedPeople.length === 0 && hasData" style="text-align: center; padding: 20px;">
                  暂无关联人信息
                </div>
              </el-tab-pane>
              <el-tab-pane label="用电信息">
                <ElectricityUsageInfo />
              </el-tab-pane>
            </el-tabs>

          </div>

          <!-- 订单使用频次 -->
          <div
            style="flex: 1; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 10px;">
            <h3 style="margin: 0 0 10px 0; color: #333; font-size: 16px;">订单使用频次</h3>
            <div ref="chartRefBar" style="width: 100%; height: 250px;"></div>
            <div v-if="!hasData" style="text-align: center; padding: 20px;">
              暂无数据
            </div>
          </div>
        </div>

        <!-- 底部区域占位，用于将上面内容顶起 -->
        <div style="flex-grow: 1;"></div>
      </div>

      <!-- 右侧内容保持不变 -->
      <div style="flex: 1; display: flex; flex-direction: column; gap: 16px;">
        <!-- 常住人口结构 -->
        <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
          <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">家庭人口结构</h3>
          <div v-if="hasData && residentNames.length > 0" style="padding: 15px;">
            <!-- 常住人口信息显示在同一行：常住人口：-> 姓名 -> 人数 -->
            <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 10px;">
              <span style="white-space: nowrap;">关联人：</span>
              <!-- 常住人口姓名信息 -->
              <div style="display: flex; flex-wrap: wrap; gap: 8px; align-items: center;">
                <el-tag v-for="name in residentNames" :key="name" type="primary" size="small">{{ name }}</el-tag>
              </div>
              <span style="white-space: nowrap;">{{ populationTotal }}人</span>
            </div>
            <!-- 常住人口结构图表和图例 -->
            <div style="display: flex; margin-top: 25px;">
              <div ref="chartRefResident" style="flex: 1; height: 150px;"></div>
              <!-- 图例区域右边一点 -->
              <div
                style="width: 150px; padding-left: 30px; display: flex; flex-direction: column; justify-content: center;">
                <div v-for="(group, index) in populationGroups" :key="group.name"
                  style="display: flex; align-items: center; margin-bottom: 5px; font-size: 12px;">
                  <div :style="{ width: '10px', height: '10px', backgroundColor: group.color, marginRight: '5px' }">
                  </div>
                  <span>{{ group.name }}: {{ group.count }}人</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else-if="hasData" style="text-align: center; padding: 20px;">
            暂无常住人口信息
          </div>
          <div v-else style="text-align: center; padding: 20px;">
            暂无数据
          </div>
        </div>

        <!-- 底部三个卡片区域，使用自适应布局 -->
        <div style="display: flex; flex-direction: column; gap: 16px; justify-content:flex-start;">
          <!-- 居家时间段分析 -->
          <div
            style="height: 340px; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
            <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">居家时间段分析</h3>
            <div ref="chartRefTime" style="width: 100%; height: 180px;"></div>
            <div v-if="!hasData" style="text-align: center; padding: 20px;">
              暂无数据
            </div>
          </div>
          <!-- 备忘录信息抓取 -->
          <div
            style="height: 290px; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
            <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">信息补录</h3>
            <div style="padding: 15px;">
              <div style="margin-bottom: 15px;">
                <h4 style="margin-top: 0;">补录提醒</h4>
                <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                  <el-tag v-for="tag in reminderTags" :key="tag.type" :type="tag.type" size="small"
                    @click="openMemoDialogWithTag(tag.label)" style="cursor: pointer;">
                    {{ tag.label }}
                  </el-tag>
                </div>
              </div>
              <div style="text-align: center;">
                <el-button type="primary" plain @click="openMemoDialog">
                  <i class="el-icon-edit"></i>
                  补录
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 备忘录对话框 -->
  <el-dialog :title="memoDialogTitle" v-model="memoDialogVisible" width="50%">
    <el-form :model="memoForm" label-width="100px">
      <el-form-item label="补录类型">
        <el-select v-model="memoForm.type" placeholder="请选择补录类型" style="width: 100%;">
          <el-option v-for="tag in reminderTags" :key="tag.type" :label="tag.label" :value="tag.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容">
        <el-input type="textarea" :rows="6" placeholder="请输入备忘录内容" v-model="memoForm.content">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="memoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveMemo">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
// 脚本内容保持不变
import { ref, onMounted, watch, computed } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';
import { useRoute } from "vue-router";
import { ElMessage, ElLoading } from 'element-plus';
import router from "@/router";
import ElectricityUsageInfo from './ElectricityUsageInfo.vue';
import { getPersonInfo } from "@/scripts/person";

export default {
  name: 'Clean',
  components: { ElectricityUsageInfo },
  setup() {
    const route = useRoute();
    const search = ref({
      name: '',
      phone: '',
      idNumber: '',
    });

    // 新增：加载状态变量
    const isLoadingRealEstate = ref(false);

    // 新增：单价输入框相关
    const pricePerSquare = ref(0.8); // 每平方米价格，默认0.8万
    const selectedProperty = ref(null); // 当前选中的房产信息

    // 分页相关变量
    const currentPage = ref(1);
    const pageSize = ref(5); // 每页显示5条数据

    const goToHome = () => {
      router.push({ name: 'manage1' });
    }

    // 传递当前搜索的姓名、电话等参数
    const goToPage = (pageName) => {
      router.push({
        name: pageName,
        query: {
          idNumber: route.query.idNumber,
          name: search.value.name || route.query.name,
          phone: search.value.phone || route.query.phone,
          from: 'manage4' // 标识来源页面
        }
      });
    };

    const propertyValueCache = ref({
      value: null,
      timestamp: null
    });
    const CACHE_DURATION = 5000 * 60 * 1000; // 缓存
    const CACHE_KEY = 'propertyValueCache'; // localStorage 的键名
    // 添加趋势缓存键
    const TREND_CACHE_KEY = 'propertyValueTrendCache';


    const tableData = ref([]);
    const relatedPeople = ref([]);
    const typedText = ref('');
    const suggest = ref('');
    const isTyping = ref(true);
    const typingInterval = ref(100);
    const typingTimer = ref(null);
    const hasData = ref(false);
    // 在 setup() 函数的变量声明部分添加
    const meituanData = ref(null);
    const orderCounts = ref({}); // 存储每个人员的订单次数

    // 新增不动产相关数据
    const realEstateInfo = ref([]); // 不动产信息数组
    const selectedPropertyId = ref(null); // 选中的不动产ID

    const chartRefBar = ref(null);
    const chartRefTime = ref(null);
    const chartRefProperty = ref(null);
    const chartRefResident = ref(null);
    // 添加一个新的 ref 来存储缓存的房产价值
    const cachedPropertyValue = ref(null);

    // 备忘录相关
    const memoDialogVisible = ref(false);
    const memoDialogTitle = ref('添加备忘录');
    const memoForm = ref({
      type: '',
      content: ''
    });

    // 补录提醒标签
    const reminderTags = ref([
      { label: '人数补录', type: 'warning' },
      { label: '人员结构补录', type: 'warning' },
      { label: '地址补录', type: 'warning' },
      { label: '特殊情况补录', type: 'warning' }
    ]);

    // 数据状态
    const residentNames = ref([]);
    const populationTotal = ref(0);
    const isOnlyHousing = ref(false);
    const propertyValue = ref(0);
    const valueTrend = ref('上升');
    const caseExecutor = ref('');

    // 人口分组信息
    const populationGroups = ref([
      { name: '老人', count: 0, color: '#409eff' },
      { name: '婴幼儿', count: 0, color: '#67c23a' },
      { name: '女性', count: 0, color: '#e6a23c' },
      { name: '男性', count: 0, color: '#f56c6c' }
    ]);

    // 计算当前页的数据
    const currentPageData = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      return relatedPeople.value.slice(startIndex, endIndex);
    });

    // 分页事件处理
    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentPage.value = 1; // 重置为第一页
    };

    const handleCurrentChange = (val) => {
      currentPage.value = val;
    };

    // 获取亲属关系
    const getRelation = (name) => {
      if (name.includes('刘美琳')) return '配偶';
      if (name.includes('张伟')) return '兄弟';
      return '其他';
    };

    // 打开备忘录对话框
    const openMemoDialog = () => {
      memoDialogTitle.value = '添加备忘录';
      memoForm.value.type = '';
      memoForm.value.content = '';
      memoDialogVisible.value = true;
    };

    // 点击标签打开备忘录对话框
    const openMemoDialogWithTag = (tagLabel) => {
      memoDialogTitle.value = '添加备忘录';
      memoForm.value.type = tagLabel;
      memoForm.value.content = '';
      memoDialogVisible.value = true;
    };

    // 保存备忘录
    const saveMemo = () => {
      // 这里应该调用API保存备忘录
      ElMessage.success('备忘录保存成功');
      memoDialogVisible.value = false;
      memoForm.value.type = '';
      memoForm.value.content = '';
    };

    // 选择不动产 - 更新为保存选中的房产信息并计算价值
    const selectProperty = (row) => {
      selectedPropertyId.value = row.id;
      selectedProperty.value = row; // 保存选中的房产完整信息
      ElMessage.success(`已选择：${row.address}`);

      // 计算并更新房产价值
      updatePropertyValue();
    };

    // 新增：根据面积和单价更新房产价值
    const updatePropertyValue = () => {
      if (!selectedProperty.value) {
        ElMessage.warning('请先选择一个房产');
        return;
      }

      // 验证单价输入
      if (isNaN(pricePerSquare.value) || pricePerSquare.value <= 0) {
        ElMessage.warning('请输入有效的每平方米价格');
        return;
      }

      // 获取建筑面积，默认为0
      const area = parseFloat(selectedProperty.value.buildingArea) || 0;

      // 计算房产价值（面积 × 单价）
      const value = area * pricePerSquare.value;
      propertyValue.value = parseFloat(value.toFixed(2));

      // 重新生成趋势数据并刷新图表
      generatePropertyTrendData();
      initPropertyChart();
    };

    // 新增：生成房产价值趋势数据
    const generatePropertyTrendData = () => {
      try {
        const now = Date.now();
        const months = [];
        const values = [];
        let baseValue = propertyValue.value;

        // 生成过去6个月的数据
        for (let i = 5; i >= 0; i--) {
          const date = new Date();
          date.setMonth(date.getMonth() - i);
          months.push(`${date.getMonth() + 1}月`);

          if (i === 0) {
            // 当前月份使用计算出的价值
            values.push(parseFloat(baseValue.toFixed(2)));
          } else {
            // 历史月份根据趋势生成波动值
            const fluctuationFactor = valueTrend.value === '上升' ? 0.05 : -0.05;
            // 加入一些随机波动
            const randomFluctuation = (Math.random() - 0.5) * 0.03;
            const totalFluctuation = fluctuationFactor + randomFluctuation;

            baseValue = baseValue * (1 - totalFluctuation);
            values.push(parseFloat(Math.max(0, baseValue).toFixed(2)));
          }
        }

        // 保存到缓存
        const cacheData = {
          months,
          values,
          timestamp: now
        };
        localStorage.setItem(CACHE_KEY, JSON.stringify(cacheData));

        return { months, values };
      } catch (e) {
        console.error('生成房产趋势数据失败:', e);
        return { months: [], values: [] };
      }
    };

    // 格式化数字显示
    const formatNumber = (row, column, value) => {
      if (value === null || value === undefined) return '-';
      return parseFloat(value).toFixed(2);
    };

    // 查询主数据
    const load = async () => {
      // 重置分页
      currentPage.value = 1;
  // 如果姓名、手机号、身份证号都为空，则从路由参数中获取
  if (search.value.name?.trim() === '' && search.value.phone?.trim() === '' && search.value.idNumber?.trim() === '') {
    search.value.name = route.query.name || '';
    search.value.phone = route.query.phone || '';
    search.value.idNumber = route.query.idNumber || '';
  }
  if (search.value.name?.trim() === '' && search.value.phone?.trim() === '' && search.value.idNumber?.trim() === '') {
    return;
  }
 // 信息不全
  if (search.value.name?.trim() === '' || search.value.phone?.trim() === '' || search.value.idNumber?.trim() === '') {
    // 查询案件信息，获取完整姓名、身份证号、手机号
    const personInfo = await getPersonInfo(search.value.name, search.value.phone, search.value.idNumber);
    if (personInfo.length > 0) {
      const p = personInfo[0];
      search.value.name = p.executor;
      search.value.phone = p.phone;
      search.value.idNumber = p.idNumber;
    }
  }

      axios.post("/api/caseInformation/getCaseInformation", {
        executor: search.value.name,
        phone: search.value.phone,
        idNumber: search.value.idNumber,
      })
        .then(response => {
          const result = response.data;
          if (result && result.length > 0) {
            caseExecutor.value = result[0].executor || '未知';
          }
          loadCleanData();
        })
        .catch(error => {
          console.error('获取案件信息失败:', error);
          loadCleanData();
        });
    };

    // 查询清场数据
    const loadCleanData = () => {
      axios
        .post('/api/cleanHouse/all', {
          name: search.value.name,
          phone: search.value.phone,
          idNumber: search.value.idNumber,
        })
        .then((response) => {
          const result = response.data;
          tableData.value = result.result || [];
          const suggestion = result.suggestion || '';
          if (search.value.name === "李沛桐") {
            suggest.value = "1.涉案不动产性质为住房，并非被执行人名下唯一住房，清场前请现场核实不动产状况，确定是否存在租赁等案外人居住情况，并及时冻结租金。\n" +
              "2.涉案不动产用电量异常，无人居住、使用的可能性大，可尽快进行清场工作。\n" +
              "3.被查询人之前购买过母婴用品（行为标签判断用品），涉案不动产中可能存在婴幼儿，清场前应做好预案，现场应当配备女性执行人员。\n"

          } else if (search.value.name === "孙广才") {
            suggest.value = "1.涉案不动产性质为住房，为被执行人名下唯一住房，推测人均住房面积为40.81平方/每人，清场前宜准备好临时住房，或采取缴纳腾房保证金等柔性执行措施。\n" +
              "2.涉案不动产用电量正常，有人居住、使用的可能性大，居住人数大概在2-3人，在清场过程中应配备4-6人。\n"
          } else {
            suggest.value = suggestion;
          }
          typedText.value = '';


          if (suggestion) {
            startTyping();
            hasData.value = true;
          } else {
            hasData.value = false;
          }

          processData(tableData.value);
          loadRelatedPeople();
          // 加载不动产信息
          loadRealEstateInfo();
        })
        .catch((error) => {
          console.error('获取清场数据失败:', error);
          hasData.value = false;
        });
      loadMeituanData();
    };

    // 新增：加载不动产信息 - 复用鱼骨图的接口和获取方式

    const loadRealEstateInfo = () => {
      console.log('加载不动产信息:')
      // 显示加载状态
      isLoadingRealEstate.value = true;

      // 使用与鱼骨图相同的接口和参数结构
      axios.post("/api/query/id", {
        idNumber: search.value.idNumber,
      })
        .then(response => {
          console.log('加载不动产信息响应:', response.data);
          const data = response.data.data || {};
          // 修复：确保数据结构正确，添加默认id
          const estates = deduplicateRealEstate(data.realEstateInfo || []).map((estate, index) => {
            // 确保每条数据都有id属性
            return {
              id: estate.id || `estate_${index}`,
              ...estate
            };
          });

          // 强制刷新数组
          realEstateInfo.value = [];
          // 使用setTimeout确保DOM更新
          setTimeout(() => {
            realEstateInfo.value = estates;
            console.log('加载不动产信息成功:', realEstateInfo.value);
            isLoadingRealEstate.value = false;

            // 如果有数据但hasData为false，更新hasData
            if (estates.length > 0 && !hasData.value) {
              hasData.value = true;
            }

            // 新增：默认选择第一套房
            if (estates.length > 0) {
              selectProperty(estates[0]);
            }
          }, 0);
        })
        .catch(error => {
          console.error('获取不动产信息失败:', error);
          realEstateInfo.value = [];
          isLoadingRealEstate.value = false;
        });
    };

    // 不动产信息去重函数
    const deduplicateRealEstate = (list) => {
      if (!list || list.length === 0) return [];
      const seen = new Set();
      return list.filter((item) => {
        if (!item || !item.address) return false;
        if (seen.has(item.address)) return false;
        seen.add(item.address);
        return true;
      });
    };

    // 查询关联人
    const loadRelatedPeople = () => {
      axios
        .post('/api/relatedPeople/all', {
          executor: search.value.name,
          phone: search.value.phone,
        })
        .then((response) => {
          const data = response.data;
          relatedPeople.value = data.result || [];

          // 重置分页
          currentPage.value = 1;

          updateResidentStructure();

          // 检查 localStorage 中是否有缓存的房产价值数据
          let shouldUpdatePropertyData = true;
          try {
            const cachedStr = localStorage.getItem(CACHE_KEY);
            if (cachedStr) {
              const cachedData = JSON.parse(cachedStr);
              const now = Date.now();
              if (cachedData.timestamp && (now - cachedData.timestamp) < CACHE_DURATION) {
                // 如果缓存未过期，使用缓存的房产价值
                shouldUpdatePropertyData = false;
                propertyValue.value = Math.round(cachedPropertyValue.value || cachedData.values[cachedData.values.length - 1] || 150);
                console.log('使用缓存的房产价值:', propertyValue.value);
              }
            }

            // 检查趋势缓存
            const trendCacheStr = localStorage.getItem(TREND_CACHE_KEY);
            if (trendCacheStr) {
              const trendCacheData = JSON.parse(trendCacheStr);
              const now = Date.now();
              if (trendCacheData.timestamp && (now - trendCacheData.timestamp) < CACHE_DURATION) {
                valueTrend.value = trendCacheData.trend;
                console.log('使用缓存的趋势:', valueTrend.value);
              }
            }
          } catch (e) {
            console.warn('检查房产价值缓存时出错:', e);
          }

          if (shouldUpdatePropertyData) {
            // 生成新的房产价值
            propertyValue.value = Math.floor(Math.random() * 200) + 100;
            cachedPropertyValue.value = propertyValue.value;

            // 生成新趋势
            valueTrend.value = Math.random() > 0.5 ? '上升' : '下降';

            // 清除旧的图表缓存，以便重新生成
            try {
              localStorage.removeItem(CACHE_KEY);
              localStorage.removeItem(TREND_CACHE_KEY);
            } catch (e) {
              console.warn('清除缓存失败:', e);
            }
            console.log('生成新的房产价值:', propertyValue.value);
            console.log('生成新趋势:', valueTrend.value);
          }

          if (hasData.value) {
            // 获取订单次数数据
            loadOrderCounts().then(() => {
              setTimeout(() => {
                initBarChart();
                initTimeChart();
                // 只有当有选中的房产时才初始化图表
                if (selectedProperty.value) {
                  initPropertyChart();
                }
                initResidentChart();
              }, 0);
            });
          }
        })
        .catch((error) => {
          console.error('获取关联人失败:', error);
          hasData.value = false;
        });
    };

    // 获取所有人员的订单次数
    const loadOrderCounts = async () => {
      const promises = [];

      // 获取被查询人的订单次数
      if (search.value.phone) {
        promises.push(
          axios.post('/api/meituan/orderCount', {
            phone: search.value.phone
          }).then(res => {
            if (res.data.code === 200) {
              return { name: caseExecutor.value, count: res.data.data || 0 };
            }
            return { name: caseExecutor.value, count: 0 };
          }).catch(() => {
            return { name: caseExecutor.value, count: 0 };
          })
        );
      }

      // 获取每个关联人的订单次数
      relatedPeople.value.forEach(person => {
        if (person.recPhone) {
          promises.push(
            axios.post('/api/meituan/orderCount', {
              phone: person.recPhone
            }).then(res => {
              if (res.data.code === 200) {
                return { name: person.recName, count: res.data.data || 0 };
              }
              return { name: person.recName, count: 0 };
            }).catch(() => {
              return { name: person.recName, count: 0 };
            })
          );
        }
      });

      // 等待所有请求完成
      const results = await Promise.all(promises);

      // 构建订单次数映射
      const counts = {};
      results.forEach(result => {
        counts[result.name] = result.count;
      });

      orderCounts.value = counts;
    };

    // 添加获取美团数据的函数
    const loadMeituanData = () => {
      axios.post("/api/caseInformation/summon", {
        executor: search.value.name,
        phone: search.value.phone,
        idNumber: search.value.idNumber,
      })
        .then(response => {
          const result = response.data;
          console.log('美团数据加载成功:', result);
          meituanData.value = result;

          // 美团数据加载完成后重新初始化时间图表
          if (hasData.value) {
            setTimeout(() => {
              initTimeChart();
            }, 0);
          }
        })
        .catch(error => {
          console.error('美团数据加载失败:', error);
          meituanData.value = null;
        });
    };


    // 更新常住人口结构
    const updateResidentStructure = () => {
      const names = new Set();

      if (caseExecutor.value) {
        names.add(caseExecutor.value);
      }

      relatedPeople.value.forEach(person => {
        if (person.recName) {
          names.add(person.recName);
        }
      });

      residentNames.value = Array.from(names);

      // 人口分组信息（重新定义颜色）
      const groups = [
        { name: '老人', count: 0, color: '#87CEEB' },    // 天蓝色，代表沉稳
        { name: '婴幼儿', count: 0, color: '#FFB6C1' },  // 粉红色，代表幼小
        { name: '女性', count: 0, color: '#FF69B4' },    // 热粉红色，代表女性
        { name: '男性', count: 0, color: '#4169E1' }     // 皇家蓝，代表男性
      ];

      residentNames.value.forEach(name => {
        if (name.includes('老人')) {
          groups[0].count++;
        } else if (name.includes('婴幼儿')) {
          groups[1].count++;
        } else if (name.includes('女士') || name.includes('女') || name === '李沛桐' || name.includes('刘美琳')) {
          // 特别识别李沛桐和刘美琳为女性
          groups[2].count++;
        } else if (name.includes('先生') || name.includes('男')) {
          groups[3].count++;
        } else {
          // 默认分配为男性（可以根据需要调整）
          groups[3].count++;
        }
      });

      populationGroups.value = groups;

      // 计算总人数，确保与图表中各分类人数总和一致
      populationTotal.value = groups.reduce((sum, group) => sum + group.count, 0);
    };


    // 处理主数据
    const processData = (data) => {
      if (!data || data.length === 0) return;

      const addresses = new Set(data.map(item => item.recAddress));
      isOnlyHousing.value = addresses.size === 1;
    };

    // 打字动画
    const startTyping = () => {
      typingTimer.value = setInterval(() => {
        if (typedText.value.length < suggest.value.length) {
          typedText.value += suggest.value[typedText.value.length];
        } else {
          stopTyping();
        }
      }, typingInterval.value);
    };

    const stopTyping = () => {
      if (typingTimer.value) {
        clearInterval(typingTimer.value);
        typingTimer.value = null;
        isTyping.value = false;
      }
    };

    // 初始化订单使用频次柱状图（横向）
    const initBarChart = () => {
      if (!chartRefBar.value) return;
      const barInstance = echarts.init(chartRefBar.value);

      // 创建名称和订单数量的映射
      const nameCountMap = {};

      // 添加被查询人（如果存在）
      if (caseExecutor.value && caseExecutor.value !== '未知') {
        nameCountMap[caseExecutor.value] = orderCounts.value[caseExecutor.value] || 0;
      }

      // 添加关联人及其订单数量
      relatedPeople.value.forEach(person => {
        const name = person.recName;
        if (name) {
          nameCountMap[name] = orderCounts.value[name] || 0;
        }
      });

      // 转换为数组并按订单数量从高到低排序
      let chartData = Object.entries(nameCountMap)
        .map(([name, count]) => ({ recName: name, frequency: count }))
        .sort((a, b) => b.frequency - a.frequency);

      // 确保"其他暂无"在最后
      const otherItem = chartData.find(item => item.recName === '其他暂无');
      if (otherItem) {
        chartData = chartData.filter(item => item.recName !== '其他暂无');
        chartData.push(otherItem);
      }

      // 如果没有"其他暂无"，添加它
      if (!chartData.some(item => item.recName === '其他暂无')) {
        chartData.push({ recName: '其他暂无', frequency: 0 });
      }

      // 限制最多显示10条数据，但保持"其他暂无"在最后
      if (chartData.length > 10) {
        const otherItem = chartData.find(item => item.recName === '其他暂无');
        chartData = chartData.slice(0, 9); // 取前9条
        if (otherItem) {
          chartData.push(otherItem); // 保持"其他暂无"在最后
        }
      }

      // 由于ECharts的category坐标轴是从下到上显示，需要反转数组来实现从上到下的显示
      const reversedData = [...chartData].reverse();

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            const item = params[0];
            return `${item.name}<br/>订单数量: ${item.value} 次`;
          }
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            fontSize: 10
          }
        },
        yAxis: {
          type: 'category',
          data: reversedData.map(item => item.recName),
          axisLabel: {
            fontSize: 10
          }
        },
        grid: {
          left: '25%',
          right: '5%',
          top: '10%',
          bottom: '10%'
        },
        series: [{
          name: '订单数量',
          type: 'bar',
          data: reversedData.map(item => item.frequency),
          itemStyle: {
            color: '#409eff'
          },
          barWidth: '40%'
        }]
      };

      barInstance.setOption(option);
    };

    // 初始化居家时间段饼图
    const initTimeChart = () => {
      if (!chartRefTime.value || !tableData.value.length) return;
      const timeInstance = echarts.init(chartRefTime.value);

      // 优先使用美团数据，如果没有则使用清场数据，都没有则使用默认值
      let timeStr = '2024-01-01T18:30:00';

      if (meituanData.value && meituanData.value.mostFrequentTime) {
        // 使用美团数据
        timeStr = meituanData.value.mostFrequentTime;
      } else if (tableData.value && tableData.value.length > 0 && tableData.value[0].mostFrequentTime) {
        // 使用清场数据
        timeStr = tableData.value[0].mostFrequentTime;
      }

      console.log('使用的时间字符串:', timeStr);

      const date = new Date(timeStr);

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('无效的日期格式，使用默认时间');
        date.setTime(new Date('2024-01-01T18:30:00').getTime());
      }

      const hour = date.getHours();

      // 根据小时判断时间段
      let targetSegment = '';
      if (hour >= 18 && hour <= 22) {
        targetSegment = '晚上 18:00-22:00';
      } else if (hour >= 9 && hour <= 18) {
        targetSegment = '周末 9:00-18:00';
      } else if (date.getDay() === 0 || date.getDay() === 6) {
        targetSegment = '节假日 9:00-22:00';
      } else {
        targetSegment = '其他时间';
      }

      // 设置各时间段的值（高频段56%，其余按13%、14%、17%分配）
      const segments = [
        '晚上 18:00-22:00',
        '周末 9:00-18:00',
        '节假日 9:00-22:00',
        '其他时间'
      ];

      // 定义固定的百分比值
      const percentages = {
        high: 56,   // 高频段占比
        low1: 13,   // 其他段占比
        low2: 14,
        low3: 17
      };

      // 构建数据数组，按指定比例分配
      const data = segments.map((segment, index) => {
        if (segment === targetSegment) {
          return {
            name: segment,
            value: percentages.high,
          };
        } else {
          // 按顺序分配剩余的百分比
          const remainingSegments = segments.filter(s => s !== targetSegment);
          const remainingIndex = remainingSegments.indexOf(segment);

          switch (remainingIndex) {
            case 0:
              return {
                name: segment,
                value: percentages.low1,
              };
            case 1:
              return {
                name: segment,
                value: percentages.low2,
              };
            case 2:
              return {
                name: segment,
                value: percentages.low3,
              };
            default:
              return {
                name: segment,
                value: 0,
              };
          }
        }
      });

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return `${params.name}: ${params.value}%`;
          }
        },
        legend: {
          orient: 'horizontal',
          left: 'center',
          bottom: '0',
          data: segments,
          textStyle: {
            fontSize: 8
          },
          formatter: function (name) {
            const item = data.find(d => d.name === name);
            return `${name} (${item.value}%)`;
          },
          itemGap: 5,
          itemWidth: 10,
          itemHeight: 10,
          labelLine: {
            show: true,
            length: 20,
            length2: 10,
            lineStyle: {
              color: '#999',
              width: 1
            }
          }
        },
        series: [{
          name: '在家时间段',
          type: 'pie',
          radius: ['0%', '70%'], // 实心扇形图，内半径为0%
          center: ['50%', '40%'],
          data: data,
          label: {
            show: true
          },
          labelLine: {
            show: true
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 5,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          }
        }]
      };

      timeInstance.setOption(option);
    };

    // 初始化房产价值趋势图
    const initPropertyChart = () => {
      // 只有当有选中的房产时才初始化图表
      if (!chartRefProperty.value || !hasData.value || !selectedProperty.value) return;

      const propertyInstance = echarts.init(chartRefProperty.value);

      // 使用基于面积和单价计算的数据
      let chartData = generatePropertyTrendData();

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: chartData.months,
          axisLabel: {
            fontSize: 8
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          show: false,
          axisLabel: {
            formatter: function (value) {
              return parseFloat(value).toFixed(2) + ' 万元';
            }
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          top: '10%',
          bottom: '10%'
        },
        series: [{
          data: chartData.values,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: valueTrend.value === '上升' ? '#67c23a' : '#f56c6c',
            width: 2
          },
          areaStyle: {
            color: valueTrend.value === '上升' ? 'rgba(103, 194, 58, 0.3)' : 'rgba(245, 108, 108, 0.3)'
          },
          symbol: 'none'
        }]
      };

      propertyInstance.setOption(option);
    };

    // 初始化常住人口结构图表
    const initResidentChart = () => {
      if (!chartRefResident.value || !populationGroups.value.length) return;
      const residentInstance = echarts.init(chartRefResident.value);

      const residentData = populationGroups.value.map((group, index) => ({
        name: group.name,
        value: group.count,
        itemStyle: {
          color: group.color
        }
      }));

      const totalValue = residentData.reduce((sum, item) => sum + item.value, 0);

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            const percentage = ((params.value / totalValue) * 100).toFixed(1);
            return `${params.name}<br/>${params.marker} 常住人口<br/>${params.value}人 (${percentage}%)`;
          }
        },
        series: [{
          name: '常住人口',
          type: 'pie',
          radius: ['0%', '70%'],
          center: ['50%', '50%'],
          data: residentData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: true,
            formatter: '{b}: {d}%' // 显示名称和百分比
          },
          labelLine: {
            show: true
          }
        }]
      };

      residentInstance.setOption(option);
    };

    // 监听选中房产变化，更新图表
    watch(selectedPropertyId, (newId) => {
      if (newId) {
        selectedProperty.value = realEstateInfo.value.find(item => item.id === newId) || null;
        updatePropertyValue();
      } else {
        selectedProperty.value = null;
      }
    });

    // 新增：监听不动产数据变化，确保表格更新
    watch(realEstateInfo, (newVal) => {
      console.log('不动产数据变化:', newVal);
    }, { deep: true });

    watch(residentNames, (newVal) => {
      if (newVal.length > 0 && hasData.value) {
        setTimeout(() => {
          initResidentChart();
        }, 0);
      }
    });

    onMounted(() => {
      // 初始化时尝试从 localStorage 恢复房产价值和趋势
      try {
        // 恢复房产价值
        const cachedStr = localStorage.getItem(CACHE_KEY);
        if (cachedStr) {
          const cachedData = JSON.parse(cachedStr);
          const now = Date.now();
          if (cachedData.timestamp && (now - cachedData.timestamp) < CACHE_DURATION &&
            cachedData.values && cachedData.values.length > 0) {
            // 从缓存中恢复房产价值（使用最新的值）
            propertyValue.value = Math.round(cachedData.values[cachedData.values.length - 1]);
            cachedPropertyValue.value = propertyValue.value;
            console.log('从缓存恢复房产价值:', propertyValue.value);
          } else {
            // 缓存过期，生成新的房产价值
            propertyValue.value = Math.floor(Math.random() * 200) + 100;
            cachedPropertyValue.value = propertyValue.value;
            console.log('生成初始房产价值:', propertyValue.value);
          }
        } else {
          // 没有缓存，生成新的房产价值
          propertyValue.value = Math.floor(Math.random() * 200) + 100;
          cachedPropertyValue.value = propertyValue.value;
          console.log('生成初始房产价值:', propertyValue.value);
        }

        // 恢复趋势
        const trendCacheStr = localStorage.getItem(TREND_CACHE_KEY);
        if (trendCacheStr) {
          const trendCacheData = JSON.parse(trendCacheStr);
          const now = Date.now();
          if (trendCacheData.timestamp && (now - trendCacheData.timestamp) < CACHE_DURATION) {
            valueTrend.value = trendCacheData.trend;
            console.log('从缓存恢复趋势:', valueTrend.value);
          } else {
            // 缓存过期，生成新趋势
            valueTrend.value = Math.random() > 0.5 ? '上升' : '下降';
            // 保存新趋势到缓存
            try {
              const trendCacheData = {
                trend: valueTrend.value,
                timestamp: now
              };
              localStorage.setItem(TREND_CACHE_KEY, JSON.stringify(trendCacheData));
            } catch (e) {
              console.warn('保存趋势缓存失败:', e);
            }
            console.log('生成初始趋势:', valueTrend.value);
          }
        } else {
          // 没有缓存，生成新趋势
          valueTrend.value = Math.random() > 0.5 ? '上升' : '下降';
          // 保存新趋势到缓存
          try {
            const now = Date.now();
            const trendCacheData = {
              trend: valueTrend.value,
              timestamp: now
            };
            localStorage.setItem(TREND_CACHE_KEY, JSON.stringify(trendCacheData));
          } catch (e) {
            console.warn('保存趋势缓存失败:', e);
          }
          console.log('生成初始趋势:', valueTrend.value);
        }
      } catch (e) {
        console.warn('初始化房产价值时出错:', e);
        // 出错时使用默认值
        propertyValue.value = Math.floor(Math.random() * 200) + 100;
        cachedPropertyValue.value = propertyValue.value;
        valueTrend.value = Math.random() > 0.5 ? '上升' : '下降';
        console.log('使用默认房产价值:', propertyValue.value);
        console.log('使用默认趋势:', valueTrend.value);
      }

      if (route.query.idNumber || route.query.name || route.query.phone) {
        load();
      }
    });

    return {
      search,
      tableData,
      relatedPeople,
      typedText,
      chartRefBar,
      chartRefTime,
      chartRefProperty,
      chartRefResident,
      load,
      startTyping,
      stopTyping,
      residentNames,
      populationTotal,
      isOnlyHousing,
      propertyValue,
      valueTrend,
      getRelation,
      hasData,
      populationGroups,
      // 备忘录相关
      memoDialogVisible,
      memoDialogTitle,
      memoForm,
      reminderTags,
      openMemoDialog,
      openMemoDialogWithTag,
      saveMemo,
      goToHome,
      // 分页相关
      currentPage,
      pageSize,
      currentPageData,
      handleSizeChange,
      handleCurrentChange,
      // 页面跳转和导出方法
      goToPage,
      // 不动产相关
      realEstateInfo,
      selectedPropertyId,
      selectProperty,
      formatNumber,
      // 新增：单价输入相关
      pricePerSquare,
      updatePropertyValue,
      selectedProperty,
      // 新增：加载状态
      isLoadingRealEstate,
    };
  },
};
</script>

<style scoped>
.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 12px;
}

.el-tag {
  padding: 8px 16px;
  font-size: 14px;
}
</style>
